package com.ck.client.service.impl;

import com.ck.client.dao.DeviceHeartBeatMapper;
import com.ck.client.model.vo.DeviceHeartBeatVO;
import com.ck.client.service.DeviceHeartBeatService;
import com.ck.core.cache.redis.RedisCacheDao;
import com.ck.core.constant.CacheConstant;
import com.ck.core.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 设备心跳service impl
 * @Author: hf
 * @Date:    2019/5/14 16:23
 * @Version: 1.0
 */
@Service(value = "deviceHeartBeatService")
public class DeviceHeartBeatServiceImpl implements DeviceHeartBeatService {

	@Autowired
	private RedisCacheDao redisCacheDao;

	@Autowired
	private DeviceHeartBeatMapper deviceHeartBeatMapper;

	@Override
	public void online(String deviceCode, Long lastReportTime) {
		if ( StringUtils.isBlank(deviceCode) ) {
			return ;
		}

		// 已有上线记录缓存，不做任何处理。
		Long onlineTime = (Long) redisCacheDao.getCache(CacheConstant.CACHE_NAME_CK_DEVICE_ONLINE, deviceCode);
		if ( onlineTime != null ) {
			return ;
		}

		// 转换上线记录时间
		String online = DateUtils.longTimeStampToStringDate(lastReportTime, DateUtils.PATTEN_YMD_HMS);

		// 获取年月日
		String markDate = DateUtils.longTimeStampToStringDate(lastReportTime, DateUtils.PATTEN_YMD);
		int effect = deviceHeartBeatMapper.online( deviceCode, online, markDate );
		if ( effect > 0 ) {

			// 上线时添加缓存记录
			redisCacheDao.putCache(CacheConstant.CACHE_NAME_CK_DEVICE_ONLINE, deviceCode,lastReportTime);
			// 缓存设置过期时间-次日0时0分0秒
			redisCacheDao.expireAt(CacheConstant.CACHE_NAME_CK_DEVICE_ONLINE, DateUtils.getMinDateOfDay(DateUtils.getNextNumDay(new Date(),1)));
		}
	}

	@Override
	public void offline(List<String> deviceCodes) throws ParseException {
		List<DeviceHeartBeatVO> records = deviceHeartBeatMapper.getByDeviceCode(deviceCodes);
		if ( records != null && !records.isEmpty() ) {
			Long now = System.currentTimeMillis();
			String offline = DateUtils.longTimeStampToStringDate(now, DateUtils.PATTEN_YMD_HMS);
			for ( DeviceHeartBeatVO r : records ) {
				r.setOffline(offline);
				r.setTotal(DateUtils.getTimeStampDiff(DateUtils.stringTimeToLongTimeStamp(r.getOnline(),DateUtils.PATTEN_YMD_HMS),now));

				// 离线时移除缓存记录
				redisCacheDao.deleteByKey(CacheConstant.CACHE_NAME_CK_DEVICE_ONLINE,r.getDeviceCode());
			}

			//  更新数据库
			Map<String ,Object> map = new HashMap<>();
			map.put("list",records);
			deviceHeartBeatMapper.offline(map);

		}

	}
}
